package com.sto.stoapp.thread;

import java.util.List;

import android.content.Context;
import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.OrderManager;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.http.URLActions;
import com.sto.stoapp.http.request.download.OrdeDownResquest;
import com.sto.stoapp.http.response.download.OrderDownResponse;
import com.sto.stoapp.http.response.download.info.OrderRecordInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.util.Helper;

/**
 * 订单下载
 * 
 * @author huangbing
 * 
 */
public class OrderDownThread extends BaseThread {
    int messageType;
	private Handler handler;
	private Context context;

	public OrderDownThread(Context context, Handler handler,int messageType) {
		super(context);
		this.handler = handler;
		this.context = context;
		this.messageType=messageType;
	}

	@Override
	public void run() {
		super.run();
		OrdeDownResquest request = new OrdeDownResquest(context);
		HttpManager mgr = new HttpManager();
		String str = mgr.doPostClient(request.buildToRequestString(),
				StoFilePreference.getInstance(context).getServerIp()
						+ URLActions.ORDER_DOWNLOAD_ACTION);
		Gson gs = new Gson();
		OrderDownResponse response = null;
		try {
			response = gs.fromJson(str, new TypeToken<OrderDownResponse>() {
			}.getType());
			OrderManager orderDownMgr = OrderManager.getInstance(context);
			List<OrderRecordInfo> infos = response.orderRecord;

			orderDownMgr.insertOrReplace(infos);

			orderDownMgr.deleteDataByStatus("20");
			orderDownMgr.deleteDataByStatus("30");
			orderDownMgr.deleteDataByStatus("40");

			showMsg("收到订单：" + infos.size() + "条");

		} catch (Exception e) {
			e.printStackTrace();
			showMsg("订单下载失败");
			ExceptionLog.writeLog("OrderDownThread", "下载失败:" + e.toString());
			return;
		}finally{
			StoDownServer.removeDownType(messageType);
		}

	}

	private void showMsg(final String text) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				Helper.showToast(context, text);
			}
		});
	}
}
